var linkedByIndex = {};
var node;
var link;
var links = new Array();
var nodes = {};

function testDrawD3(result){
	var people = result.people;
	var neighbors = result.relation_neighbor;
	var colleagues = result.relation_colleague;
	var relatives = result.relation_relative;
	
	
	
	
	for(var i = 0; i < people.length; i++){
		nodes[people[i].name] = {
				"name" : people[i].name,
				"age" : people[i].age,
				"address" : people[i].address,
				"sex" : people[i].sex,
				"email" : people[i].email
		}
	}
	
	for(var i = 0; i < colleagues.length; i++){
		var nodeSingle = {
				"source" : nodes[colleagues[i].src],
				"target" : nodes[colleagues[i].dest],
				"relation" : "colleague"
		}
		links.push(nodeSingle);
	}
	
	for(var i = 0; i < neighbors.length; i++){
		var nodeSingle = {
				"source" : nodes[neighbors[i].src],
				"target" : nodes[neighbors[i].dest],
				"relation" : "neighbor"
		}
		links.push(nodeSingle);
	}
	for(var i = 0; i < relatives.length; i++){
		var nodeSingle = {
				"source" : nodes[relatives[i].src],
				"target" : nodes[relatives[i].dest],
				"relation" : "relative"
		}
		links.push(nodeSingle);
	}
	
	
	var width = 900;
    var height = 600;
    var linkdistance = 300;
    var chargeNum = -1000;
    var gravity = 0.4;
    var force;
    
    
    force =  d3.layout.force()           		//创建基于物理模拟的位置连接
			    .nodes(d3.values(nodes))  		//获得或设置布局中的节点（node）阵列组。
			    .links(links)            		//获得或设置布局中节点间的连接（Link）阵列组。
   force.size([width, height])   		//获取或设置布局的 宽 和 高 的大小.
	    .linkStrength(1)				//值为1，则拖动一个顶点A，与之相连的顶点会与A保持linkDistance设定的距离运动
	    								//值为0，则拖动一个顶点A，与之相连的顶点不会运动，连接线会被拉长
	    .linkDistance(linkdistance)    //获取或设置节点间的连接线距离
	    .charge(chargeNum)             //获取或设置节点的电荷数.(电荷数决定结点是互相排斥还是吸引, 正数吸引，负数排斥)
	    .gravity(0.2)
		.theta(0.9)
		.alpha(0)
		.on("tick", tick)
	    .start();
    
   

	var svg = d3.select("#d3part")
				.append("svg")
				.attr("width", width)
				.attr("height", height);


	link = svg.append("svg:g").selectAll("path")  
				    .data(force.links()) 
				  	.enter().append("svg:path")
				    .attr("class", function(d) { 
						if(d.relation == "neighbor") {
							return "link neighbor";
						} else if(d.relation == "relative") {
							return "link relative";
						}else {
							return "link colleague";
						};    
					})/*.append("text")
					.attr("class","linetext")
					.text(function(d){
						return d.relation;
					})*/;
	
	/*var edges_text = svg.selectAll(".linetext")
						.data(force.links())
						.enter()
						.append("text")
						.attr("class","linetext")
						.text(function(d){
							return d.relation;
						});*/
	
	/*var line_text =  svg.selectAll(".linetext")
						.data(force.links())
						.enter()
						.append("text")
						.attr("class","linetext")
						.text(function(d){
							return d.relation;
						});*/


	
	// drag pin
    var node_drag = d3.behavior.drag()
                .on("dragstart", dragstart)
                .on("drag", dragmove)
                .on("dragend", dragend);

    function dragstart(d, i) {
        force.stop(); // stops the force auto positioning before you start dragging
    }

    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }

    function dragend(d, i) {
        d.fixed = true; //拖动完成后是否定在完成地点
        force.resume();
    }

    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }

	//(4)为链接添加节点  
	node = svg.selectAll(".node")  
				.data(force.nodes())  
				.enter()
				.append("g")  
				.attr("class", "node") 
				.attr('cursor','pointer')
				.on('click',connectedNodes)
	            .on("mouseover", mouseover)  
	            .on("mouseout", mouseout)
//	            .on("rightclick", function(d){
//	            	alert(d.name);
//	            })
//	            .on('dblclick', goDetail)
				.call(node_drag);
	
	
	
	node.append("circle")
        .attr("cx", function(d){
        	return "-" + 5 + "px";
        })  
        .attr("cy", function(d){
        	return "-" + 5 + "px";
        })
        .attr("r", function(d){
        	return 20 + "px";
        })
        .attr("fill", "pink")
        .style("opacity", 1);  

	
	
	
	//设置提示  
	node.append("text")  
		.text(function(d) { 
			return d.name;
		})
		.attr("x", "15px")
		.attr("y", "15px")
		.style("font-size",  "8px")
		.style("fill",  "grey")
		.style("font-family",  "微软雅黑");
	
	//force.stop();
	
	function tick() {
		//限制结点的边界
//		var img_w = 20;
//		var img_h = 20;
//		var text_dx = -20;
//		var text_dy = 20;
		d3.values(nodes).forEach(function(d,i){
//			console.log(d3.select(this).select("circle").attr("r"))
//			d.x = d.x - img_w/2 < 0     ? img_w/2 : d.x ;
//			d.x = d.x + img_w/2 > width ? width - img_w/2 : d.x ;
			d.x = d.x < 0 ? 10 : d.x;
			d.x = d.x > width ? width : d.x;
			d.y = d.y < 0 ? 10 : d.y;
			d.y = d.y > height ? height : d.y;
//			d.y = d.y - img_h/2 < 0      ? img_h/2 : d.y ;
//			d.y = d.y + img_h/2 + text_dy > height ? height - img_h/2 - text_dy : d.y ;
		});

			
		//打点更新坐标  
		link.attr("d", function(d) {  
		    var dx = d.target.x - d.source.x,//����  
		        dy = d.target.y - d.source.y,  
		        dr = Math.sqrt(dx * dx + dy * dy); 
		    
		    ha = "";
		     
		    
		    if(d.relation == "neighbor") {
		    	ha = 0 + "," + 0;
			} else if(d.relation == "relative") {
				ha = dr*2 + "," + dr*2;
			}else {
				ha = dr + "," + dr;
			};   
			
			return "M" + d.source.x + ","   
		    + d.source.y + "A" + ha + " 0 0 1 " + d.target.x + ","   
		    + d.target.y; 
		    
		  });
			
		node.attr("transform", function(d) {   
			return "translate(" + d.x + "," + d.y + ")";   
		});
		
		//更新连接线上文字的位置
//		 edges_text.attr("x",function(d){ return (d.source.x + d.target.x) / 2 ; });
//		 edges_text.attr("y",function(d){ return (d.source.y + d.target.y) / 2 ; });
	}
	
	
	function mouseover() {  
		  d3.select(this).select("circle").transition()  
		      .duration(200)  
		      .attr("r", function(d){  //设置圆点半径                        
		    return 30;                            
//		    return radius (d)+10;                            
		 }) ;  
		}  
		  
		function mouseout() {  
		  d3.select(this).select("circle").transition()  
		      .duration(750)  
		      .attr("r", function(d){  //恢复圆点半径                        
		    return 15;                            
//		    return radius (d);                            
		 }) ;  
		}  
		
		var toggle = 0;
		
		
		var node_len = 0;
		for(var nod in nodes){
			node_len++;
		}
		
	    for (i = 0; i < node_len; i++) {
	        linkedByIndex[i + "," + i] = 1;
	    };
	    
	    links.forEach(function (d) {
	        linkedByIndex[d.source.index + "," + d.target.index] = 1;
	    });
		
	    //This function looks up whether a pair are neighbours  
	    function neighboring(a, b) {
	        return linkedByIndex[a.index + "," + b.index];
	    }
		
	    function connectedNodes() {
	    	var ss = [23, 23, 34, 12, 56];
	    	//__data__属性将数据与图形绑定，获取图形附带的数据
	    	//d = d3.select(this).node().__data__;
	    	/*d3.select("#d3part")
	    	  .selectAll("span")
	    	  .data(ss)
	    	  .enter()
	    	  .append("span")
	    	  .style("display", "block")
			  .style("width", function(d){
					console.log("d: ", d);
					return d + "px";
				})
			  .style('height', '30px')
			  .style("background", "pink")
			  .style("position", "relative")
			  .style('z-index', 9999);*/
	    	alert("哈哈哈");
	    	
	    	var n_nodes = {};
	    	for(var i = 0; i < ss.length; i++){
	    		var nn = "jolin" + ss[i];
	    		n_nodes[nn] = {
	    				"name" : nn,
	    				"age" : ss[i],
	    				"address" : "",
	    				"sex" : "女",
	    				"email" : ""
	    		}
	    	}
	    	var n_nodes = svg.selectAll(".node")
					    	.data(n_nodes)
					    	.enter()
					    	.append("g")
					    	.attr("class", "node")
					    	.attr('cursor','pointer');
		    
	    	n_nodes.append("circle")
		        .attr("cx", function(d){
		        	return "-" + 5 + "px";
		        })  
		        .attr("cy", function(d){
		        	return "-" + 5 + "px";
		        })
		        .attr("r", function(d){
		        	return 20 + "px";
		        })
		        .attr("fill", "green")
		        .style("opacity", 1);  
 
	    	
	    	
	        /*if (toggle == 0) {
	            //Reduce the opacity of all but the neighbouring nodes
	            //d is the selected one, and 
	            
	            node.style("opacity", function (o) {
	                return neighboring(d, o) | neighboring(o, d) ? 1 : 0.0;
	            });
	            
	            link.style("opacity", function (o) {
	                return d.index==o.source.index | d.index==o.target.index ? 1 : 0.0;
	            });
	            //Reduce the op
	            
	            toggle = 1;
	        } else {
	            //Put them back to opacity=1
	            node.style("opacity", 1);
	            link.style("opacity", 1);
	            toggle = 0;
	        }
	    }*/
	    }
	
}



function showNeighbors(){
    link.style("opacity", function (o) {
    	if(o.relation != "neighbor"){
    		return 0;
    	} else {
    		return 1;
    	}
    });
}


function showColleagues(){
	link.style("opacity", function (o) {
		if(o.relation != "colleague"){
			return 0;
		} else {
			return 1;
		}
	});
}


function showRelatives(){
	link.style("opacity", function (o) {
		if(o.relation != "relative"){
			return 0;
		} else {
			return 1;
		}
	});
}

function showAll(){
	link.style("opacity", 1);
}
